﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorldEvolution
{
    public static class UUIDHelp
    {
        static UInt32 sIndex = 0;
        static UInt16 sProcessUID = (UInt16)(new Random()).Next(); //一个进程一个id,需要保证进程间ID不同,若不指定，则随机生成
        readonly static object _sync = new object();
        static System.DateTime saveTime = new System.DateTime(2014, 1, 1);
        public static void InitServerID(UInt16 id) { sProcessUID = id;}

        const uint cMaxIndex = 1 << 22;
        //id是64位的（时间戳：32位；ProcessUID：11位；序列号：21位）
        public static ulong GenerateUUID()
        {
            lock (_sync)
            {
                var span = System.DateTime.Now - saveTime;
                UInt32 ts = (UInt32)span.TotalSeconds;
                UInt64 objId = (UInt64)( ((UInt64)(ts) << 32) | ((UInt64)(sProcessUID) << 18) | ((UInt64)(++sIndex)));

                if (sIndex >= cMaxIndex)
                    sIndex = 0;
                return objId;
            }
        }
    }
}
